package com.czl.module_base.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.SizeUtils;
import com.czl.base.data.bean.tengyun.CategoryBean;
import com.czl.module_base.R;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author xubin
 */
public class CategoryAdapter extends ListTreeAdapter<CategoryAdapter.BaseViewHolder> {

    private OnItemClickListener mOnItemClickListener;
    private boolean mOnlySelectedLastLevel;
    private final HashSet<Integer> ids = new HashSet<>();

    public CategoryAdapter() {
        super();
        tree = new ListTree();
    }

    public CategoryAdapter(ListTree tree) {
        super(tree);
    }

    public CategoryAdapter(ListTree tree, float indentation) {
        super(tree, indentation);
    }

    @SuppressLint("NotifyDataSetChanged")
    public void addAll(List<CategoryBean> list) {
        for (CategoryBean bean : list) {
            //创建组们，是root node，所有parent为null
            bean.setLevel(0);
            Set<Integer> categoryIds = new HashSet<>();
            categoryIds.add(bean.getId());
            bean.setChildIds(categoryIds);
            bean.setParentName(bean.getName());
            bean.setParentAbsoluteId(String.valueOf(bean.getId()));
            ListTree.TreeNode groupNode = tree.addNode(null, bean, R.layout.item_category_parent);
            groupNode.setExpand(false);
            List<CategoryBean> children = bean.getChildren();
            if (children == null) {
                continue;
            }
            for (CategoryBean childrenBean : children) {
                List<CategoryBean> childrenXs = childrenBean.getChildren();
                Set<Integer> childIds = new HashSet<>();
                childrenBean.setLevel(1);
                childrenBean.setChildIds(childIds);
                childIds.add(childrenBean.getId());
                categoryIds.add(childrenBean.getId());
                childrenBean.setParentAbsoluteId(bean.getId() + "," + childrenBean.getId());
                childrenBean.setParentName(bean.getName() + "-" + childrenBean.getName());
                ListTree.TreeNode treeNode1 = tree.addNode(groupNode, childrenBean, R.layout.item_category_children);
                treeNode1.setExpand(false);
                if (childrenXs == null) {
                    continue;
                }
                for (CategoryBean childrenBeanX : childrenXs) {
                    //第三层
                    categoryIds.add(childrenBean.getId());
                    childIds.add(childrenBean.getId());
                    childrenBeanX.setParentAbsoluteId(bean.getId() + "," + childrenBean.getId() + "," + childrenBeanX.getId());
                    childrenBeanX.setParentName(bean.getName() + "-" + childrenBean.getName() + "-" + childrenBeanX.getName());
                    childrenBeanX.setLevel(2);
                    ListTree.TreeNode n = tree.addNode(treeNode1, childrenBeanX, R.layout.item_category_children);
                    n.setExpand(false);
                }
            }
        }
        notifyDataSetChanged();
    }

    public <T> void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    @NonNull
    @Override
    protected CategoryAdapter.BaseViewHolder onCreateNodeView(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        //创建不同的行View
        if (viewType == R.layout.item_category_parent) {
            //注意！此处有一个不同！最后一个参数必须传true！
            View view = inflater.inflate(viewType, parent, false);
            //用不同的ViewHolder包装
            return new CategoryAdapter.GroupViewHolder(view);
        } else if (viewType == R.layout.item_category_children) {
            //注意！此处有一个不同！最后一个参数必须传true！
            View view = inflater.inflate(viewType, parent, false);
            //用不同的ViewHolder包装
            return new CategoryAdapter.ContactViewHolder(view);
        } else {
            return null;
        }
    }

    @Override
    protected void onBindNodeViewHolder(CategoryAdapter.BaseViewHolder viewHolder, int position) {
        ListTree.TreeNode node = tree.getNodeByPlaneIndex(position);
        if (node.getLayoutResId() == R.layout.item_category_parent) {
            //group node
            CategoryBean parentInfo = (CategoryBean) node.getData();
            GroupViewHolder gvh = (GroupViewHolder) viewHolder;
            gvh.tvParentName.setText(parentInfo.getName());
            int childCount = node.getChildrenCount();
            setViewHolder(gvh.tvParentName, gvh.ivParent, node, viewHolder, childCount);
        } else if (node.getLayoutResId() == R.layout.item_category_children) {
            //child node
            CategoryBean info = (CategoryBean) node.getData();
            ContactViewHolder cvh = (ContactViewHolder) viewHolder;
            cvh.tvName.setText(info.getName());
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) cvh.ivParent.getLayoutParams();
            int level = info.getLevel() == null ? 0 : info.getLevel();
            layoutParams.setMarginStart(SizeUtils.dp2px(35 + 20 * (level - 1)));
            cvh.ivParent.setLayoutParams(layoutParams);
            int childCount = info.getChildren() == null ? 0 : info.getChildren().size();
            setViewHolder(cvh.tvName, cvh.ivParent, node, viewHolder, childCount);
        }
    }

    private void setViewHolder(TextView textView, ImageView imageView, ListTree.TreeNode node,
                               CategoryAdapter.BaseViewHolder viewHolder, int childCount) {
        if (childCount == 0) {
            imageView.setVisibility(View.INVISIBLE);
        } else {
            imageView.setVisibility(View.VISIBLE);
        }
        if (node.isExpand()) {
            imageView.setImageResource(R.drawable.ic_collapse);
        } else {
            imageView.setImageResource(R.drawable.ic_zhankai);
        }
        textView.setOnClickListener(v -> clickItem(node, viewHolder));
        imageView.setOnClickListener(v -> expandItem(viewHolder));
    }

    private void viewClickItem(View view, CategoryAdapter.BaseViewHolder viewHolder, ListTree.TreeNode treeNode) {
        view.setOnClickListener(v -> {
            expandItem(viewHolder);
            if (treeNode.getChildrenCount() == 0) {
                clickItem(treeNode, viewHolder);
            }
        });
    }

    private void expandItem(BaseViewHolder viewHolder) {
        int planePos = viewHolder.getLayoutPosition();
        ListTree.TreeNode treeNode = tree.getNodeByPlaneIndex(planePos);
        int nodePlaneIndex = tree.getNodePlaneIndex(treeNode);
        if (treeNode.isExpand()) {
            //收起
            int count = tree.collapseNode(nodePlaneIndex);
            notifyItemChanged(nodePlaneIndex);
            //通知view将相关的行删掉
            notifyItemRangeRemoved(nodePlaneIndex + 1, count);
        } else {
            //展开
            int count = tree.expandNode(nodePlaneIndex);
            notifyItemChanged(nodePlaneIndex);
            //通知view插入相关的行
            notifyItemRangeInserted(nodePlaneIndex + 1, count);
        }
    }

    private void clickItem(ListTree.TreeNode node1, BaseViewHolder viewHolder) {
        ListTree.TreeNode parent = node1.getParent();
        String title;
        String pIdPath;
        CategoryBean categoryBean;
        if (parent != null) {
            ListTree.TreeNode parent1 = parent.getParent();
            if (parent1 != null) {
                Object data1 = parent1.getData();
                CategoryBean parentData = (CategoryBean) parent.getData();
                //三级索引
                CategoryBean data = (CategoryBean) node1.getData();
                if (data1 instanceof CategoryBean) {
                    title = ((CategoryBean) data1).getName() + "-" + parentData.getName() + "-" + data.getName();
                    pIdPath = ((CategoryBean) data1).getId() + "," + parentData.getId() + "," + data.getId();
                } else {
                    title = parentData.getName() + "-" + data.getName();
                    pIdPath = parentData.getId() + "," + data.getId();
                }
                categoryBean = data;
            } else {
                //二级索引
                CategoryBean data = (CategoryBean) node1.getData();
                if (parent.getData() instanceof CategoryBean) {
                    CategoryBean info = (CategoryBean) parent.getData();
                    title = info.getName() + "-" + data.getName();
                    pIdPath = info.getId() + "," + data.getId();
                } else {
                    title = data.getName();
                    pIdPath = String.valueOf(data.getId());
                }
                categoryBean = data;
                if (!lastLevel(data) && mOnlySelectedLastLevel) {
                    expandItem(viewHolder);
                    return;
                }
            }
        } else {
            //一级索引
            CategoryBean data = (CategoryBean) node1.getData();
            title = data.getName();
            pIdPath = String.valueOf(data.getId());
            categoryBean = data;
            if (!lastLevel(data) && mOnlySelectedLastLevel) {
                expandItem(viewHolder);
                return;
            }
        }
        ids.clear();
        addIds(categoryBean);
        categoryBean.setChildIds(ids);
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(categoryBean, title, pIdPath);
        }
    }

    private void addIds(CategoryBean categoryBean) {
        if (categoryBean == null) {
            return;
        }
        ids.add(categoryBean.getId());
        if (categoryBean.getChildren() == null || categoryBean.getChildren().isEmpty()) {
            return;
        }
        for (CategoryBean bean : categoryBean.getChildren()) {
            addIds(bean);
        }
    }

    private boolean lastLevel(CategoryBean data) {
        return data.getChildren() == null || data.getChildren().isEmpty();
    }

    public void setOnlySelectedLastLevel(boolean onlySelectedLastLevel) {
        mOnlySelectedLastLevel = onlySelectedLastLevel;
    }

    protected class BaseViewHolder extends ListTreeAdapter.ListTreeViewHolder {
        public BaseViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class GroupViewHolder extends BaseViewHolder {
        TextView tvParentName;
        ImageView ivParent;

        public GroupViewHolder(View itemView) {
            super(itemView);
            tvParentName = itemView.findViewById(R.id.tv_name);
            ivParent = itemView.findViewById(R.id.iv_name);
        }
    }

    private class ContactViewHolder extends BaseViewHolder {
        TextView tvName;
        ImageView ivParent;

        public ContactViewHolder(View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_name);
            ivParent = itemView.findViewById(R.id.iv_name);
        }
    }
}